﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Practices.Unity;

namespace ERPStore.Web.IOC
{
	public class UnityDependencyResolver : System.Web.Mvc.IDependencyResolver, ERPStore.IOC.IDependencyResolver
	{
		private System.Web.Mvc.IDependencyResolver m_DefaultDependencyResolver;

		public UnityDependencyResolver(Microsoft.Practices.Unity.IUnityContainer container)
		{
			this.Container = container;
			this.m_DefaultDependencyResolver = System.Web.Mvc.DependencyResolver.Current;
		}

		public Microsoft.Practices.Unity.IUnityContainer Container { get; private set; }

		public object GetService(Type serviceType)
		{
			object instance = null;
			if (IsBuiltIn(serviceType))
			{
				return m_DefaultDependencyResolver.GetService(serviceType);
			}
			instance = Container.Resolve(serviceType);
			return instance;
		}

		public IEnumerable<object> GetServices(Type serviceType)
		{
			if (IsBuiltIn(serviceType))
			{
				return m_DefaultDependencyResolver.GetServices(serviceType);
			}
			return Container.ResolveAll(serviceType);
		}

		private bool IsBuiltIn(Type serviceType)
		{
			if (serviceType == typeof(System.Web.Mvc.ModelMetadataProvider)
				|| serviceType == typeof(System.Web.Mvc.IControllerFactory)
				|| serviceType == typeof(System.Web.Mvc.IControllerActivator)
				|| serviceType == typeof(System.Web.Mvc.ITempDataProvider)
				|| serviceType == typeof(System.Web.Mvc.Async.IAsyncActionInvoker)
				|| serviceType == typeof(System.Web.Mvc.IActionInvoker)
				|| serviceType == typeof(System.Web.Mvc.IViewPageActivator)
				)
			{
				return true;
			}
			return false;
		}


	}
}
